package com.artisan.provider.controller;


import com.github.pagehelper.PageInfo;
import com.artisan.provider.utils.JWTUtils;
import com.artisan.provider.bane.CurrentUser;
import com.artisan.provider.bane.LoginResult;
import com.artisan.provider.contanent.Contanents;
import com.artisan.provider.covtransformation.CovUserTransformation;
import com.artisan.provider.domain.*;
import com.artisan.provider.service.ZgUserService;
import com.artisan.provider.utils.QiNiuYunUtils;
import com.artisan.provider.utils.Request;
import com.artisan.provider.vo.UserCountListVo;
import com.artisan.provider.vo.ZgUserPoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
public class ZgUserController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    ZgUserService zgService;

    @Autowired
    QiNiuYunUtils qiNiuYunUtils;


    @GetMapping(value = "/api/user/regustory")
    public List<ZgUserInfo> UserRegustory(){

        List<ZgUserInfo> list = new ArrayList<ZgUserInfo>();
        list.add(new ZgUserInfo(1,"用户1","123456","13923815937@163.com","88888888","广东省深圳市",32));
        list.add(new ZgUserInfo(1,"用户1","123456","13923815937@163.com","13923815937","广东深圳",1));
        System.out.println("数据返回");
        return list;

    }

    /**
     * 查询所有用户
     * @return
     */
    @PostMapping(value = "/api/user/findAll/{page}/{limit}")
    public RPage<ZgUserPoVo> userFinAll(
            @PathVariable(value = "page",required = false)int page,
            @PathVariable(value = "limit",required = false)int limit,
            @RequestBody(required = false)ZgUser zgUser, HttpServletRequest request){

        String authorization = request.getHeader("Authorization");

        System.out.println(authorization);

        List<ZgUser> zgUsers = zgService.userFindAll(page,limit,zgUser);

        PageInfo<ZgUser> zgUserPageInfo = new PageInfo<>(zgUsers);
        RPage<ZgUserPoVo> zgUserPoVoRPage = CovUserTransformation.INSTANCE.rPagePoVo(zgUserPageInfo);
        return zgUserPoVoRPage;
    }

    /**
     * 注册新用户
     * @param zgUser
     * @return
     */
    @PostMapping(value = "/api/user/add/userInfo")
    public Request addUserInfo(@RequestBody ZgUser zgUser){
        System.out.println(zgUser.getIpAddress());
        //!not ipAddress
        if (zgUser.getIpAddress() == null){
            return new Request(Contanents.IP_ADDRESS_NO,false,null);
        }

        //get redisIP
        String first = redisTemplate.opsForValue().get("ipAddress");

        if (first != null){
            if (first.equals(zgUser.getIpAddress())){
                return new Request(Contanents.DO_NOT_SUBMIT_REPEATEDLY,false,null);
            }
        }

        //set ipAddress
        redisTemplate.opsForValue().set("ipAddress",zgUser.getIpAddress(),60, TimeUnit.SECONDS);

        int i = zgService.userAddUserInfo(zgUser);
        if(i == 1){
            return new Request(Contanents.DATA_ADDED_SUCCESSFULLY,true,i);
        }else{
            return new Request(Contanents.FAILED_TO_ADD_DATA,false,i);
        }
    }

    @PostMapping(value = "/api/gz/user/findAll")
    public List<ZgUser> userFindAll(@RequestBody(required = false) ZgUser zgUser){
        return zgService.userFindAllList(zgUser);
    }

    /**
     * springboot 整合redis- ip限流
     * @return
     */
    @PostMapping(value = "/api/add/user/info/list")
    public String userAddUserInfoList(@RequestBody(required = false)ZgUser zgUser){

        //判断是否有ip地址
        if (zgUser.getIpAddress() == null){
            return "ip地址不能为空";
        }

        //获取redis,查看是否有ip地址重复添加 防止恶塞数据
        String first = redisTemplate.opsForValue().get("ipAddress");
        int i = 1;
        if (first != null){
            System.out.println("防止恶塞数据"+i+1);
            return "请勿重复提交";
        }

        System.out.println("存入数据成功");
        //存入ip地址
        redisTemplate.opsForValue().set("ipAddress",zgUser.getIpAddress(),5, TimeUnit.SECONDS);

        return "数据存入成功";
    }

    /***
     * 后台管理登陆接口
     * @param object
     * @return
     */
    @PostMapping(value = "/login/account")
    public LoginResult loginAccount(@RequestBody Object object){

        System.out.println(object);
        return new LoginResult("ok","account","asdflkj");

    }

    /**
     * 后台管理登陆校验
     */
    @PostMapping(value = "/api/user/login/currentUser")
    public DataCurrentUser currentUser(@RequestBody(required = false)ZgUser zgUser){
        DataCurrentUser dataCurrentUser = new DataCurrentUser();
        CurrentUser currentUser = new CurrentUser();
        ZgUserJurisdiction zgUser1 = zgService.userLoginCurrentUser(zgUser);
        if (zgUser1 == null){
            return dataCurrentUser;
        }else{
            currentUser.setAccess(zgUser1.getAdminUserName());
            currentUser.setName(zgUser1.getAdminUserName());
            currentUser.setTitle("");
            currentUser.setMenuList(zgUser1.getMenuList());
            dataCurrentUser.setData(currentUser);
            String token = JWTUtils.geneJsonWebToken(zgUser1);
            System.out.println(token);
            // set redis
            redisTemplate.opsForValue().set(Contanents.JWT_LOGIN+zgUser1.getId().toString(),token.toString(),5*24*60*60,TimeUnit.SECONDS);
            dataCurrentUser.setToken(token);
            dataCurrentUser.setSuccess(true);
            return dataCurrentUser;
        }
    }

    /**
     * 获取所有用户信息
     */
    @GetMapping(value = "/rule")
    public List<ZgUser> zgUserListFindAll( @RequestBody(required = false) Object object
                                          ){
        int page = 1;
        int limit = 20;
        ZgUser zgUser = new ZgUser();

        return zgService.zgUserListFindAll(zgUser,page,limit);
    }

    /**
     * 新用户限时折扣
     * @param zgCoupon
     * @return
     */
    @PostMapping(value = "/redis/time")
    public String redisTime(@RequestBody(required = false) ZgCoupon zgCoupon){
        int leftTime = Math.toIntExact(System.currentTimeMillis() / 1000);
        //实时监听redis时间
        String first = redisTemplate.opsForValue().get(zgCoupon.getZgUserId().toString());
        if (first != null){
            int time = (Integer.valueOf(first) - Integer.valueOf(leftTime));
            System.out.println("redis监听获取"+time);
            return Integer.toString(time);
        }
        //存入7天的倒计时
        int time = 7*24*60*60;
        long timeLone = System.currentTimeMillis();

        int rightTime = Math.toIntExact(System.currentTimeMillis() / 1000) + time;
        String stringTime = rightTime +"";
        //存入用户id
        redisTemplate.opsForValue().set(zgCoupon.getZgUserId().toString(),stringTime,time, TimeUnit.SECONDS);
        //存入数据库。。。。。

        String first2 = redisTemplate.opsForValue().get(zgCoupon.getZgUserId().toString());
        int tim2e = (Integer.valueOf(first2) - Integer.valueOf(leftTime));
        return Integer.toString(tim2e);

    }

    /**
     * 用户登陆
     * @param zgUser
     * @return
     */
    @PostMapping(value = "/api/user/login")
    public Request apiUserLogin(@RequestBody ZgUser zgUser){

        System.out.println(zgUser);
        return null;
    }

    /**
     * 获取单个用户信息
     * @param id
     * @return
     */
    @GetMapping(value = "/api/user/getid/{id}")
    public ZgUser apiUserGetId(@PathVariable(value = "id")int id){

        return zgService.userGetId(id);
    }

    /**
     * user list
     * @return
     */
    @PostMapping(value = "/api/user/info/find/list")
    public List<ZgUser> userInfoFindList(){

        return zgService.userInfoFindList();
    }

    /**
     * 修改用户信息
     * @param zgUser
     * @return
     */
    @PutMapping(value = "/api/user/update")
    public int userUpdate(@RequestBody(required = false) ZgUser zgUser){
        zgUser.setUpdateTime(System.currentTimeMillis()+"");
        System.out.println(zgUser);
        return zgService.userUpdate(zgUser);
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping(value = "/api/user/delete/{id}")
    public int userDeleteId(@PathVariable(value = "id")int id){
        return zgService.userDeleteId(id);
    }

    /**
     * 后台管理新增用户
     * @param zgUser
     * @return
     */
    @PostMapping(value = "/api/user/input/add")
    public int userInputAdd(@RequestBody ZgUser zgUser){
        try{
            zgUser.setdFlag(0);
            zgUser.setCreateTime(System.currentTimeMillis()+"");
            return zgService.userInputAdd(zgUser);
        }catch (Exception e){
            return 0;
        }
    }

    /**
     * 请求头
     * @param request
     * @param zgUser
     * @return
     */
    @PostMapping(value = "/api/user/login/account")
    public LoginResult userLoginAccount(HttpServletRequest request,@RequestBody(required = false)ZgUser zgUser){
        String header = request.getHeader("Content-Type");
        String token = request.getHeader("token");
        String authToken = request.getHeader("Authorization");
        System.out.println(zgUser);
        System.out.println(request);
        System.out.println(authToken);

        return new LoginResult("ok","account","asdf;lkj");
    }

    /**
     * 统计用户人数(区域划分)
     */
    @GetMapping(value = "/api/user/address/count/list")
    public UserCountListVo userAddressCountList(){

        UserCountListVo userCountLIstVo = zgService.userAddCountList();
        return userCountLIstVo;
    }

    /**
     * 文件上传
     */
    @RequestMapping("/uploadPictures") //uploadPictures 这里的接口
    @ResponseBody
    public String uploadPictures(MultipartFile file){

        //System.out.println(files);
        System.out.println("进来了");
        String url = "";
        if (file != null) {
           // for (int i = 0; i < files.length; i++) {
                try {

                    //System.out.println(files);
                    FileInputStream fileInputStream = (FileInputStream) file.getInputStream();

                    url = qiNiuYunUtils.uploadQiniuYun(fileInputStream);

                    try {
                        //延迟两秒让七牛云缓一下 2000 等于2秒 不能缓的时间太长,前端没有渲染到图片会报错
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
           // }
        }
        System.out.println("返回图片地址"+url);
        //上传图片成功
        return url;
    }

    /**
     * 用户增长趋势    7天  15天   30天
     */


    /**
     * 访问量统计    7天内用户访问  15天内用户访问  30内用户访问
     */


    /**
     * 用户的年龄统计  1到18岁   18到25岁  25到35岁  .....
     */





}
